using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;
using System.Drawing;
using demo.Tool;

namespace demo
{
    /// <summary>
    /// 转介卡处理窗体：支持时间范围查询（最大30天）、数据显示与用户信息展示
    /// </summary>
    public partial class ReferralCardForm : Form
    {
        private readonly UesrModel _userInfo;
        private readonly UserLoginManager.UserDeptInfo _deptInfo;
        private List<PatientDataService.ReferralCardInfoItem> _allItems = new List<PatientDataService.ReferralCardInfoItem>();

        private static bool IsDesignMode()
        {
            return LicenseManager.UsageMode == LicenseUsageMode.Designtime
                   || System.Diagnostics.Process.GetCurrentProcess().ProcessName.Equals("devenv", StringComparison.OrdinalIgnoreCase);
        }

        public ReferralCardForm() : this(null) { }

        public ReferralCardForm(UesrModel userInfo)
        {
            _userInfo = userInfo;
            _deptInfo = (_userInfo != null) ? UserLoginManager.GetUserDeptInfo(_userInfo.user_id) : new UserLoginManager.UserDeptInfo { DeptName = string.Empty, OrgCode = string.Empty };

            InitializeComponent();
            if (!IsDesignMode())
            {
                this.Shown += ReferralCardForm_Shown;
                this.btnQuery.Click += BtnQuery_Click;
                this.rbUnaccepted.CheckedChanged += Filter_CheckedChanged;
                this.rbAccepted.CheckedChanged += Filter_CheckedChanged;
                this.rbAll.CheckedChanged += Filter_CheckedChanged;
                dtEnd.Value = DateTime.Today;
                dtStart.Value = DateTime.Today.AddDays(-3);

                var userId = _userInfo?.user_id ?? string.Empty;
                var userName = _userInfo?.user_name ?? string.Empty;
                var deptName = _deptInfo?.DeptName ?? string.Empty;
                var orgCode = _deptInfo?.OrgCode ?? string.Empty;
                lblUserInfo.Text = $"用户ID: {userId}    姓名: {userName}    科室: {deptName} ({orgCode})";

                BuildColumns();
                dgvReferral.CellFormatting += DgvReferral_CellFormatting;
            }
        }

        private void BuildColumns()
        {
            dgvReferral.Columns.Clear();

            var btnAccept = new DataGridViewButtonColumn
            {
                Name = "colAccept",
                HeaderText = "",
                Width = 70,
                UseColumnTextForButtonValue = false,
                FlatStyle = FlatStyle.Standard
            };
            dgvReferral.Columns.Add(btnAccept);

            // 主键与患者维度
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "卡ID", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.CardInfoId), Width = 120 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "患者ID", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.PatientId), Width = 120 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "患者就诊ID", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.PatientVisitId), Width = 120 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "就诊ID", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.VisitId), Width = 90 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "患者姓名", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.PatiName), Width = 90 });

            // 科室与医生（来源与接诊）
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "来源科室", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.OrgSourceName), Width = 120 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "来源编码", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.OrgSourceCode), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "接诊科室", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.OrgDestName), Width = 120 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "接诊编码", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.OrgDestCode), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "来源医生", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpSourceName), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "医生编码", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpSourceCode), Width = 90 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "接诊医生", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpDestName), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "医生编码", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpDestCode), Width = 90 });

            // 执行信息
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "执行医生", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpExecName), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "执行编码", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpExecCode), Width = 90 });

            // 时间信息
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "申请日期", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.SourceDate), Width = 140 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "接诊日期", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.DestDate), Width = 140 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "执行时间", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.ExecDate), Width = 140 });

            // 状态与作废信息
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "状态", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.Status), Width = 70 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "作废标记", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.Invalidate), Width = 80 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "备注", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.Note), Width = 160 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "作废人编码", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpInvaliCode), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "作废人名称", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.EmpInvaliName), Width = 100 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "作废时间", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.InvaliDatetime), Width = 140 });

            // 其他
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "创建时间", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.CreateDate), Width = 140 });
            dgvReferral.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "组号", DataPropertyName = nameof(PatientDataService.ReferralCardInfoItem.GroupNo), Width = 160 });

            dgvReferral.DataBindingComplete += DgvReferral_DataBindingComplete;
            dgvReferral.CellContentClick += DgvReferral_CellContentClick;
        }

        private void ReferralCardForm_Shown(object sender, EventArgs e)
        {
            PerformQuery();
        }

        private void BtnQuery_Click(object sender, EventArgs e)
        {
            PerformQuery();
        }

        private void PerformQuery()
        {
            try
            {
                var startDate = dtStart.Value.Date;
                var endDate = dtEnd.Value.Date;

                if (endDate < startDate)
                {
                    MessageBox.Show("结束日期不能早于开始日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                var range = endDate - startDate;
                if (range.TotalDays > 30)
                {
                    MessageBox.Show("查询时间范围不能超过30天", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                string startTime = startDate.ToString("yyyy-MM-dd 00:00:00");
                string endTime = endDate.ToString("yyyy-MM-dd 23:59:59");

                var orgDestCode = _deptInfo?.OrgCode ?? string.Empty;

                var resp = PatientDataService.QueryReferralCardInfo(startTime, endTime, null, orgDestCode, null);
                if (resp == null)
                {
                    MessageBox.Show("服务器无响应", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (resp.Success != "1" || resp.Data == null)
                {
                    dgvReferral.DataSource = null;
                    MessageBox.Show(resp.Message ?? "未找到对应数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                _allItems = resp.Data?.ToList() ?? new List<PatientDataService.ReferralCardInfoItem>();
                ApplyFilterAndBind();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询转介卡信息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DgvReferral_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                ApplyRowVisuals();
            }
            catch { }
        }

        private void DgvReferral_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
                if (dgvReferral.Columns[e.ColumnIndex].Name != "colAccept") return;

                var row = dgvReferral.Rows[e.RowIndex];
                var item = row.DataBoundItem as PatientDataService.ReferralCardInfoItem;
                var cell = row.Cells[e.ColumnIndex] as DataGridViewButtonCell;
                var btnText = (cell?.Value ?? "").ToString();
                if (btnText != "接诊" || item == null) return;

                string patientId = item.PatientId ?? string.Empty;
                var masterGrid = FindMasterGrid();
                bool foundMatch = false;
                if (masterGrid != null && masterGrid.Columns.Contains("colOutpVisitId"))
                {
                    foreach (DataGridViewRow mr in masterGrid.Rows)
                    {
                        var val = mr.Cells["colOutpVisitId"].Value?.ToString() ?? string.Empty;
                        if (!string.IsNullOrEmpty(val) && string.Equals(val, patientId, StringComparison.OrdinalIgnoreCase))
                        {
                            foundMatch = true;
                            break;
                        }
                    }
                }

                string prompt = foundMatch
                    ? "请输入接诊备注（note）："
                    : "该转介患者不是您今日接诊患者，是否保存结果？请输入备注（note）：";
                using (var noteForm = new ReferralNoteForm(prompt))
                {
                    var dr = noteForm.ShowDialog(this);
                    if (dr != DialogResult.OK) return;
                    string note = noteForm.NoteText?.Trim() ?? string.Empty;

                    string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                // 接诊后置为已接诊：Status=1
                string statusToSet = "1";
                string empExecCode = _userInfo?.user_id ?? null;
                string empExecName = _userInfo?.user_name ?? null;

                    var resp = PatientDataService.UpdateReferralCardExecInfo(
                        item.CardInfoId,
                        empExecCode,
                        empExecName,
                        now,
                        statusToSet,
                        note);

                    if (resp == null || resp.Success != "1")
                    {
                        MessageBox.Show(resp?.Message ?? "更新失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    item.Note = note;
                    item.ExecDate = now;
                    if (!string.IsNullOrEmpty(empExecCode)) item.EmpExecCode = empExecCode;
                    if (!string.IsNullOrEmpty(empExecName)) item.EmpExecName = empExecName;
                    item.Status = statusToSet;

                    // 更新本地数据并刷新视图；重新应用筛选以确保行在当前筛选下正确显示/隐藏
                    RefreshReferralRow(e.RowIndex);
                    ApplyFilterAndBind();
                    MessageBox.Show("更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理接诊操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RefreshReferralRow(int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= dgvReferral.Rows.Count) return;
            var row = dgvReferral.Rows[rowIndex];
            var item = row.DataBoundItem as PatientDataService.ReferralCardInfoItem;
            var cell = row.Cells["colAccept"] as DataGridViewButtonCell;
            if (cell != null)
            {
                // 未接诊(Status=0)显示“接诊”按钮；已接诊(Status=1)不显示
                cell.Value = (item != null && item.Status == "0") ? "接诊" : string.Empty;
            }
            ApplyRowVisuals();
            dgvReferral.InvalidateRow(rowIndex);
        }

        private void ApplyFilterAndBind()
        {
            IEnumerable<PatientDataService.ReferralCardInfoItem> filtered = _allItems;
            if (rbUnaccepted.Checked)
            {
                // 未接诊：Status=0
                filtered = _allItems.Where(x => x.Status == "0");
            }
            else if (rbAccepted.Checked)
            {
                // 已接诊：Status=1
                filtered = _allItems.Where(x => x.Status == "1");
            }
            else
            {
                filtered = _allItems;
            }
            dgvReferral.DataSource = filtered.ToList();
        }

        private void Filter_CheckedChanged(object sender, EventArgs e)
        {
            ApplyFilterAndBind();
        }

        private bool IsMatchedInMaster(string patientId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(patientId)) return false;
                var masterGrid = FindMasterGrid();
                if (masterGrid == null) return false;
                if (!masterGrid.Columns.Contains("colOutpVisitId")) return false;
                foreach (DataGridViewRow mr in masterGrid.Rows)
                {
                    var val = mr.Cells["colOutpVisitId"].Value?.ToString() ?? string.Empty;
                    if (!string.IsNullOrEmpty(val) && string.Equals(val, patientId, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            catch { }
            return false;
        }

        private void ApplyRowVisuals()
        {
            try
            {
                foreach (DataGridViewRow row in dgvReferral.Rows)
                {
                    var item = row.DataBoundItem as PatientDataService.ReferralCardInfoItem;
                    var cell = row.Cells["colAccept"] as DataGridViewButtonCell;
                    if (cell != null)
                    {
                        // 未接诊(Status=0)显示“接诊”按钮；已接诊(Status=1)不显示
                        cell.Value = (item != null && item.Status == "0") ? "接诊" : string.Empty;
                    }

                    if (item != null)
                    {
                        bool matched = IsMatchedInMaster(item.PatientId ?? string.Empty);
                        row.DefaultCellStyle.BackColor = matched ? Color.LightGreen : Color.LightYellow;
                    }
                }
            }
            catch { }
        }

        private void DgvReferral_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                var col = dgvReferral.Columns[e.ColumnIndex];
                var rowItem = dgvReferral.Rows[e.RowIndex].DataBoundItem as PatientDataService.ReferralCardInfoItem;
                if (rowItem == null) return;

                if (string.Equals(col.DataPropertyName, nameof(PatientDataService.ReferralCardInfoItem.Status), StringComparison.Ordinal))
                {
                    // 正确显示：0=未接诊，1=已接诊
                    e.Value = rowItem.Status == "1" ? "已接诊" : "未接诊";
                    e.FormattingApplied = true;
                }
                else if (string.Equals(col.DataPropertyName, nameof(PatientDataService.ReferralCardInfoItem.Invalidate), StringComparison.Ordinal))
                {
                    e.Value = rowItem.Invalidate == "1" ? "有效" : "无效";
                    e.FormattingApplied = true;
                }
            }
            catch { }
        }

        private DataGridView FindMasterGrid()
        {
            try
            {
                foreach (Form f in Application.OpenForms)
                {
                    var dg = FindControlRecursive(f, "dgv_master") as DataGridView;
                    if (dg != null) return dg;
                }
            }
            catch { }
            return null;
        }

        private Control FindControlRecursive(Control parent, string name)
        {
            if (parent == null) return null;
            if (parent.Name == name) return parent;
            foreach (Control c in parent.Controls)
            {
                var r = FindControlRecursive(c, name);
                if (r != null) return r;
            }
            return null;
        }
    }
}